using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
using AndroidX.Core.App;
using AndroidX.Core.Content;
using System.Text;

namespace AndroidApp2
{
    /// <summary>
    /// 主活动类 - 应用的入口活动
    /// 负责应用界面的初始化和前台服务的启动
    /// </summary>
    [Activity(Label = "@string/app_name", MainLauncher = true)]
    public class MainActivity : Activity, ISocketStateCallback
    {
        /// <summary>
        /// 日志显示的TextView控件
        /// </summary>
        private TextView? _logTextView;
        
        /// <summary>
        /// 日志内容StringBuilder
        /// </summary>
        private StringBuilder _logBuilder = new StringBuilder();
        
        /// <summary>
        /// 滚动视图控件
        /// </summary>
        private ScrollView? _scrollView;
        
        /// <summary>
        /// 日志管理器
        /// </summary>
        private LogManager _logManager = LogManager.Instance;

        /// <summary>
        /// Socket管理器
        /// </summary>
        private SocketManager? _socketManager;

        /// <summary>
        /// Socket控制按钮
        /// </summary>
        private Button? _btnStartSocket;
        private Button? _btnStopSocket;
        
        /// <summary>
        /// 通知控制按钮
        /// </summary>
        private Button? _btnStartNotification;
        private Button? _btnStopNotification;
        /// <summary>
        /// 活动创建时的回调方法
        /// 在这里进行活动的初始化工作，包括界面设置和服务启动
        /// </summary>
        /// <param name="savedInstanceState">保存的实例状态，用于恢复活动状态</param>
        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            
            LogMessage("OnCreate: 活动正在创建");

            // 从"main"布局资源设置我们的视图
            SetContentView(Resource.Layout.activity_main);
            
            // 初始化日志显示控件
            InitializeLogDisplay();
            
            // 初始化控制按钮
            InitializeButtons();
            

            // 订阅日志事件
            _logManager.LogMessageReceived += OnLogMessageReceived;

            // 初始化Socket管理器
            _socketManager = new SocketManager();
            _socketManager.SetCallback(this);

            LogMessage("OnCreate: 布局已设置，准备启动前台服务");
            
            // 启动前台服务
            StartForegroundService();

            ForegroundService.OnNotificationStateChanged += OnNotificationStateChanged;

            LogMessage("OnCreate: 活动创建完成");
        }
        
        /// <summary>
        /// 日志消息事件处理
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">日志消息事件参数</param>
        private void OnLogMessageReceived(object? sender, LogMessageEventArgs e)
        {
            RunOnUiThread(() =>
            {
                _logBuilder.AppendLine(e.Message);
                if (_logTextView != null)
                {
                    _logTextView.Text = _logBuilder.ToString();
                    
                    // 自动滚动到底部
                    _scrollView?.Post(() =>
                    {
                        _scrollView.FullScroll(Android.Views.FocusSearchDirection.Down);
                    });
                }
            });
        }
        
        /// <summary>
        /// 初始化控制按钮
        /// </summary>
        private void InitializeButtons()
        {
            // Socket控制按钮
            _btnStartSocket = FindViewById<Button>(Resource.Id.btnStartSocket);
            _btnStopSocket = FindViewById<Button>(Resource.Id.btnStopSocket);
            
            // 通知控制按钮
            _btnStartNotification = FindViewById<Button>(Resource.Id.btnStartNotification);
            _btnStopNotification = FindViewById<Button>(Resource.Id.btnStopNotification);
            
            // 设置按钮点击事件
            if (_btnStartSocket != null)
            {
                _btnStartSocket.Click += (sender, e) =>
                {
                    LogMessage("用户点击启动Socket按钮");
                    _ = Task.Run(async () => await _socketManager?.ConnectAsync());
                };
            }
            
            if (_btnStopSocket != null)
            {
                _btnStopSocket.Click += (sender, e) =>
                {
                    LogMessage("用户点击停止Socket按钮");
                    _socketManager.Dispose();
                };
            }
            
            if (_btnStartNotification != null)
            {
                _btnStartNotification.Click += (sender, e) =>
                {
                    LogMessage("用户点击启动通知按钮");
                    ForegroundService.StartTimedNotification();
                };
            }
            
            if (_btnStopNotification != null)
            {
                _btnStopNotification.Click += (sender, e) =>
                {
                    LogMessage("用户点击停止通知按钮");
                    ForegroundService.StopTimedNotification();
                };
            }
            
            LogMessage("InitializeButtons: 控制按钮初始化完成");
        }
        
        /// <summary>
        /// 实现IServiceControlCallback接口，接收服务状态变化
        /// </summary>
        /// <param name="isConnected">Socket连接状态</param>
        public void OnSocketStateChanged(bool isConnected)
        {
            RunOnUiThread(() =>
            {
                if (_btnStartSocket != null && _btnStopSocket != null)
                {
                    _btnStartSocket.Enabled = !isConnected;
                    _btnStopSocket.Enabled = isConnected;
                }
                LogMessage($"OnSocketStateChanged: Socket状态变更 - {(isConnected ? "已连接" : "未连接")}");
            });
        }

        /// <summary>
        /// Socket消息接收回调
        /// </summary>
        /// <param name="message">消息内容</param>
        public void OnSocketMessageReceived(string message)
        {
            _logManager.LogSocket(message);
        }

        /// <summary>
        /// Socket错误回调
        /// </summary>
        /// <param name="error">错误信息</param>
        public void OnSocketError(string error)
        {
            _logManager.LogError(error, "Socket");
        }
        /// <summary>
        /// 实现IServiceControlCallback接口，接收通知状态变化
        /// </summary>
        /// <param name="isRunning">通知运行状态</param>
        public void OnNotificationStateChanged(bool isRunning)
        {
            RunOnUiThread(() =>
            {
                if (_btnStartNotification != null && _btnStopNotification != null)
                {
                    _btnStartNotification.Enabled = !isRunning;
                    _btnStopNotification.Enabled = isRunning;
                }
                LogMessage($"OnNotificationStateChanged: 通知状态变更 - {(isRunning ? "已启动" : "未启动")}");
            });
        }
        
        /// <summary>
        /// 初始化日志显示控件
        /// </summary>
        private void InitializeLogDisplay()
        {
            _logTextView = FindViewById<TextView>(Resource.Id.logTextView);
            _scrollView = FindViewById<ScrollView>(Resource.Id.logScrollView);
            
            if (_logTextView != null)
            {
                _logTextView.Text = "日志开始...\n";
                _logBuilder.AppendLine("日志开始...");
                LogMessage("InitializeLogDisplay: 日志显示控件初始化完成");
            }
        }
        
        /// <summary>
        /// 添加日志消息到界面显示
        /// </summary>
        /// <param name="message">日志消息</param>
        private void LogMessage(string message)
        {
            _logManager.LogActivity(message);
        }
        
        /// <summary>
        /// 启动前台服务的私有方法
        /// 处理权限检查和服务启动逻辑
        /// </summary>
        private void StartForegroundService()
        {
            LogMessage("StartForegroundService: 开始启动前台服务");
            
            // 检查并请求通知权限（Android 13+）
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
            {
                if (ContextCompat.CheckSelfPermission(this, Android.Manifest.Permission.PostNotifications) 
                    != Android.Content.PM.Permission.Granted)
                {
                    LogMessage("StartForegroundService: 需要请求通知权限");
                    // 请求通知权限
                    ActivityCompat.RequestPermissions(this, 
                        new[] { Android.Manifest.Permission.PostNotifications }, 1);
                    return;
                }
            }
            
            LogMessage("StartForegroundService: 权限检查通过，启动服务");
            // 使用 ServiceManager 启动前台服务
            ServiceManager.StartForegroundService(this);
            LogMessage("StartForegroundService: 前台服务启动完成");
        }
        
        /// <summary>
        /// 权限请求结果回调方法
        /// 处理用户对权限请求的响应，根据结果决定是否启动服务
        /// </summary>
        /// <param name="requestCode">请求码，用于标识不同的权限请求</param>
        /// <param name="permissions">请求的权限列表</param>
        /// <param name="grantResults">权限授予结果列表</param>
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            
            LogMessage($"OnRequestPermissionsResult: 请求码={requestCode}, 权限数量={permissions.Length}");
            
            // 检查是否是通知权限请求的响应
            if (requestCode == 1)
            {
                if (grantResults.Length > 0 && grantResults[0] == Android.Content.PM.Permission.Granted)
                {
                    LogMessage("OnRequestPermissionsResult: 通知权限已获得，启动前台服务");
                    // 权限已获得，启动前台服务
                    ServiceManager.StartForegroundService(this);
                    LogMessage("OnRequestPermissionsResult: 前台服务已启动");
                }
                else
                {
                    LogMessage("OnRequestPermissionsResult: 通知权限被拒绝，无法启动前台服务");
                }
            }
        }
        
        // ========== 生命周期事件 ==========
        
        /// <summary>
        /// 活动启动时调用
        /// </summary>
        protected override void OnStart()
        {
            base.OnStart();
            LogMessage("OnStart: 活动已启动，对用户可见");
        }
        
        /// <summary>
        /// 活动恢复时调用（获得焦点）
        /// </summary>
        protected override void OnResume()
        {
            base.OnResume();
            LogMessage("OnResume: 活动已恢复，可以与用户交互");
        }
        
        /// <summary>
        /// 活动暂停时调用（失去焦点）
        /// </summary>
        protected override void OnPause()
        {
            base.OnPause();
            LogMessage("OnPause: 活动已暂停，失去焦点");
        }
        
        /// <summary>
        /// 活动停止时调用（不可见）
        /// </summary>
        protected override void OnStop()
        {
            base.OnStop();
            LogMessage("OnStop: 活动已停止，对用户不可见");
        }
        
        /// <summary>
        /// 活动重新启动时调用
        /// </summary>
        protected override void OnRestart()
        {
            base.OnRestart();
            LogMessage("OnRestart: 活动正在重新启动");
        }
        
        /// <summary>
        /// 活动销毁时调用
        /// </summary>
        protected override void OnDestroy()
        {
            LogMessage("OnDestroy: 活动正在销毁，清理资源");
            
            // 取消订阅日志事件
            _logManager.LogMessageReceived -= OnLogMessageReceived;
            
            LogMessage("OnDestroy: 资源清理完成");
            
            base.OnDestroy();
        }
        
        /// <summary>
        /// 处理新的Intent（当活动已存在时）
        /// </summary>
        /// <param name="intent">新的Intent对象</param>
        protected override void OnNewIntent(Intent? intent)
        {
            base.OnNewIntent(intent);
            LogMessage($"OnNewIntent: 收到新的Intent - Action: {intent?.Action ?? "null"}");
        }
        
        /// <summary>
        /// 处理返回键按下事件
        /// </summary>
        public override void OnBackPressed()
        {
            LogMessage("OnBackPressed: 用户按下返回键");
            base.OnBackPressed();
        }
        
        /// <summary>
        /// 处理其他活动返回的结果
        /// </summary>
        /// <param name="requestCode">请求码</param>
        /// <param name="resultCode">结果码</param>
        /// <param name="data">返回的数据</param>
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent? data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            LogMessage($"OnActivityResult: 请求码={requestCode}, 结果码={resultCode}, 数据={data?.DataString ?? "null"}");
        }

    }
}